package com.fbd.apipassenger.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fbd.internalcommon.constant.TokenConstants;
import com.fbd.internalcommon.dto.ResponseResult;
import com.fbd.internalcommon.dto.TokenResult;
import com.fbd.internalcommon.util.JwtUtils;
import com.fbd.internalcommon.util.RedisPrefixUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean result = true;
        String resultString = "";
        String token = request.getHeader("Authorization");
        TokenResult tokenResult = null;
        try {
            tokenResult = JwtUtils.pareToken(token);
        } catch (Exception e) {
            resultString = "token invalid";
            result = false;
        }
        if (tokenResult == null){
            resultString = "token invalid";
            result = false;
        }else {
            // 判断token是否和redis中的一致
            String phone = tokenResult.getPhone();
            String refreshToken = RedisPrefixUtils.generatorKeyToken(phone , TokenConstants.REFRESH_TOKEN_KEY);
            String s = stringRedisTemplate.opsForValue().get(refreshToken);
            if (StringUtils.isBlank(s)){
                //
                String accessToken = RedisPrefixUtils.generatorKeyToken(phone , TokenConstants.ACCESS_TOKEN_KEY);
                String s2 = stringRedisTemplate.opsForValue().get(accessToken);
                if (s2 == null) {
                    resultString = "token invalid";
                    result = false;
                }else {
                    // 生成双token,先不做了
                }

            }else {
                // 不一致
                if (!token.trim().equals(s.trim())){
                    resultString = "token invalid";
                    result = false;
                }
            }
        }
        if (!result){
            PrintWriter writer = response.getWriter();
            writer.print(JSONObject.toJSON(ResponseResult.fail(500,resultString)).toString());
        }

        return result;
    }
}
